import { FormCard } from '@components/FormCard'
import ImagePreview from '@components/ImagePreview'
import { useFormCallback } from '@hooks/useFormCallback'
import { usePartnerCreateMutation, usePartnerUpdateMutation } from '@services/partner'
import { Link } from '@tanstack/react-router'
import { Breadcrumb, Button, Form, Input } from 'antd'
import { useEffect, useState } from 'react'

export const FormPartner = ({ defaultData }) => {
  const [data, setData] = useState(defaultData)
  const [form] = Form.useForm()
  const { mutate } = defaultData.id ? usePartnerUpdateMutation() : usePartnerCreateMutation()
  const { onFinish, onFailed } = useFormCallback(mutate, {
    handle: (values) => ({
      ...values,
      ...(defaultData.id && { id: defaultData.id }),
    }),
  })

  useEffect(() => {
    form.setFieldsValue({ ...defaultData })
  }, [])

  const card = {
    title: (
      <Breadcrumb
        items={[
          { title: '关于我们' },
          { title: <Link to="..">合作伙伴</Link> },
          { title: '新增' },
        ]}
      />
    ),
  }

  return (
    <FormCard card={card}>
      <Form
        name="basic"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: '100%' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFailed}
        autoComplete="off">
        <Form.Item
          label="合作伙伴名称"
          name="name"
          rules={[{ required: true, message: '请输入合作伙伴名称' }]}>
          <Input size="large" />
        </Form.Item>
        <Form.Item
          label="合作伙伴Logo"
          name="logo"
          rules={[{ required: true, message: '请上传合作伙伴Logo' }]}>
          <ImagePreview
            aspect="9:4"
            url={data.logo}
            onChange={(resp) => {
              setData((prev) => ({ ...prev, logo: resp.url }))
              form.setFieldsValue({ logo: resp.url })
            }}
          />
        </Form.Item>
        <Form.Item
          label="合作伙伴网址"
          name="link"
          rules={[
            { required: true, message: '请输入网址' },
            {
              pattern: /^((ht|f)tps?:\/\/)+[\w-]+(\.[\w-]+)+(:\d{1,5})?\/?$/,
              message: '请输入正确的网址,包含http://或https://',
            },
          ]}>
          <Input size="large" />
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            保 存
          </Button>
        </Form.Item>
      </Form>
    </FormCard>
  )
}
